package com.ruoyi.generator.controller.ysd;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.generator.domain.*;
import com.ruoyi.generator.service.IFromCrudBtnsService;
import com.ruoyi.generator.service.IFromCrudTableConfigService;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.generator.service.impl.FromBuildConfigServiceImpl;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.zgl.youshuda.core.utils.CustomHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色与菜单处理
 */
@RestController
public class YsdRoleMenuController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询所有角色
     */
    @GetMapping("/role/list")
    public AjaxResult selectRoleAll()
    {
        List<SysRole> sysRoles = roleService.getAllRoleMenuInfo();
        List<Map<String, Object>> result = sysRoles.stream()
                .map(role -> {
                    Map<String, Object> map = new HashMap();
                    map.put("roleId", role.getRoleId());
                    map.put("roleName", role.getRoleName());
                    map.put("dataScope", role.getDataScope());
                    return map;
                }).collect(Collectors.toList());
        return success(result);
    }

    /**
     * 修改角色与菜单绑定关系
     */
    @PostMapping("/role/menu/refresh")
    public AjaxResult refreshRoleMenu(@RequestBody List<SysRole> roles)
    {
        if (roleService.updateRoleMenu(getUsername(),roles) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色失败");
    }

    /**
     * ===================================== 用户与角色绑定信息 =====================================
     */

    /**
     * 查询所有用户信息
     */
    @GetMapping("/role/user/list")
    public AjaxResult getAllUserInfo()
    {
        List<SysUser> allUserInfo = userService.getAllUserInfo();
        List<Map<String, Object>> result = allUserInfo.stream()
                .map(user -> {
                    Map<String, Object> map = new HashMap();
                    map.put("userId", user.getUserId());
                    map.put("userName", user.getUserName());
                    map.put("roleIds", user.getRoleIds());
                    return map;
                }).collect(Collectors.toList());
        return success(result);
    }

    /**
     * 修改用户与角色绑定关系
     */
    @PostMapping("/role/user/refresh")
    public AjaxResult refreshRoleUser(@RequestBody List<SysUser> users)
    {
        return toAjax(userService.refreshRoleUser(users));
    }


    /**
     * 处理角色，当角色不存在时，则新增角色，存在时则修改
     */
    @PostMapping("/role/upsert")
    public AjaxResult upsert(@RequestBody List<SysRole> roles)
    {
        return roleService.upsert(roles);
    }



}
